package com.akk.business;


import com.akk.module.avs.entity.AvsApplyLoan;
import com.akk.module.avs.entity.AvsIncreRecord;
import com.akk.module.avs.enums.AvsIncreEnums;
import com.akk.module.avs.model.request.AvsIncreRecordRequest;
import com.akk.module.avs.service.AvsApplyLoanService;
import com.akk.module.avs.service.AvsIncreReocrdService;
import com.akk.utils.RestResponse;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AvsApplyLoanBusiness {

    @Autowired
    private AvsApplyLoanService applyLoanService;

    @Autowired
    private AvsIncreReocrdService increReocrdService;

    public RestResponse list(Integer page, Integer limit){
        if (page == null || page == 0)
            page = 1;
        if (limit == null || limit == 0)
            limit = 6;
        PageHelper.startPage(page,limit);
        Map params = new HashMap();
        params.put("notstatus",-1);
        List<AvsApplyLoan> list = applyLoanService.queryByParams(params);
        return RestResponse.build(list);
    }

    public RestResponse recom(){
        Map params = new HashMap();
        params.put("status", AvsIncreEnums.LoanStatus.RECOM.getValue());
        List<AvsApplyLoan> list = applyLoanService.queryByParams(params);
        if (list.size() == 1)
            return RestResponse.build(list.get(0));
        else
            return RestResponse.build("1","信息有误","");
    }

    public RestResponse info(@PathVariable Long loanId){
        AvsApplyLoan entity = applyLoanService.queryById(loanId);
        if (entity == null)
            return RestResponse.build("1","信息不存在","");
        return RestResponse.build(entity);
    }

    public RestResponse saveRecord(AvsIncreRecordRequest recordRequest, BindingResult bindingResult){
        if (bindingResult.hasErrors())
            return RestResponse.build("1",bindingResult.getFieldError().getDefaultMessage(),null);
        AvsIncreRecord record = new AvsIncreRecord();
        record.setRecordPhone(recordRequest.getRecordPhone());
        record.setRecordUsername(recordRequest.getRecordUsername());
        record.setType("loan");
        record.setCreateTime(new Date());
        record.setTypeId(recordRequest.getTypeId());
        increReocrdService.save(record);
        return RestResponse.build("success");
    }

}
